package com.example.config;

import com.example.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description:统一结果封装
 * User: bjc
 * Date: 2025-07-26
 * Time: 13:40
 */
@ControllerAdvice //表示是控制器通知类
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //判断是否要执行beforeBodyWrite()方法，true表示执行，false表示不执行。
        return true;
    }

    @SneakyThrows //因为方法writeValueAsString有抛出异常，所以需要处理，可以加注解，也可以使用try catch
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Result){
            return body;
        }
        if(body instanceof String){
            //对string格式特殊处理，转换为JSON字符串（为了保持统一返回格式）
            ObjectMapper objectMapper = new ObjectMapper();
            // 设置响应头为JSON格式
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);
    }
}
